package com.iflytek.cosmo.ocr.common.config;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author yxchen
 * @version 1.0
 */
@Configuration
public class ExecutorConfig {
    private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);

    @Value("${threadpool.upload.size:16}")
    private int uploadSize;

    @Bean
    public ExecutorService fastDFSUploadTheadpool() {
        return new ThreadPoolExecutor(uploadSize, uploadSize, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3000),
                new ThreadFactoryBuilder().setDaemon(false).setNameFormat("FASTDFS-UPLOAD-Thread-%d")
                                          .setUncaughtExceptionHandler(((t, e) -> logger.error("线程 " + t + " 异常结束", e)))
                                          .build(), new ThreadPoolExecutor.CallerRunsPolicy());
    }

    /**
     * 转换pdf线程池
     *
     * @return
     */
    @Bean
    public Executor pdfCreateExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(32);
        executor.setMaxPoolSize(32);
        executor.setQueueCapacity(Integer.MAX_VALUE);
        executor.setThreadNamePrefix("pdfCreate-pool-");
        executor.initialize();
        return executor;
    }

    /**
     * 删除文件线程池
     *
     * @return
     */
    @Bean
    public Executor deleteFileExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(32);
        executor.setMaxPoolSize(32);
        executor.setQueueCapacity(Integer.MAX_VALUE);
        executor.setThreadNamePrefix("deleteFileCreate-pool-");
        executor.initialize();
        return executor;
    }

}
